//package com.lt.test.consumer.controller;
//
//import com.alibaba.dubbo.config.annotation.Reference;
//import com.lt.test.api.ClearingService;
//import com.lt.test.common.constant.HttpRequestConstant;
//import com.lt.test.common.model.MinShengClearingResponseDTO;
//import com.lt.test.common.util.WeiZhi_DaiFu;
//import com.lt.test.common.util.shcs_DaiFu;
//import com.lt.test.entity.DTO.ResponseDTO;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
//import org.apache.shiro.authz.annotation.RequiresPermissions;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.ResponseBody;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.BufferedReader;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//import java.net.URLDecoder;
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * Created by zhengchuan on 2017/5/9.
// * 清算控制器
// */
//@Controller
//@RequestMapping("/clearing")
//public class ClearingController {
//    private static final Logger logger = LoggerFactory.getLogger(ClearingController.class);
//
//    @Reference(version = "1.0.0")
//    private ClearingService clearingService;
//
//    /**
//     * 民生银行代付清算
//     *
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequiresPermissions("CLEARING:DO_CLEARING")
//    @RequestMapping(value = "/minShengClearing", method = {RequestMethod.POST})
//    public @ResponseBody
//    ResponseDTO minShengClearing(HttpServletRequest request) throws Exception {
//        ResponseDTO responseDTO = new ResponseDTO();
//        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");//设置日期格式
//
//        String orderId = df.format(new Date()) + "0000";
//        String Name = request.getParameter("cardHolder");
//        String accNo = request.getParameter("bankCardNo");
//        String idCarNo = request.getParameter("idCarNo");
//        String txnAmt = request.getParameter("txnAmt");
//        String rateAmt = request.getParameter("rateAmt");
//        String merId = request.getParameter("merId");
//        String certificateCode = request.getParameter("certificateCode");
//        String clearingType = request.getParameter("clearingType");
//        String transType = request.getParameter("transType");//交易方式--微信支付宝／银联
//
//        String userId = request.getParameter("userId"); //用户
//        String orderCount = request.getParameter("orderCount");
//        String createTime = request.getParameter("createTime");
//        Long longRateAmt = Long.valueOf(rateAmt);
//        Long longTxnAmt = Long.valueOf(txnAmt);
//        Map<String, Long> clearingParams = clearingService.getClearingParams();
//        String ourRealSells = "";
//        if (clearingType.equals("2") && longTxnAmt >= clearingParams.get("minPrice")) {//300免手续费
//            //TODO 清算金额加50分
//            longRateAmt+= clearingParams.get("cost");
//            ourRealSells = "0";
//        }else {
//            longRateAmt = longRateAmt-(clearingParams.get("sells") - clearingParams.get("cost"));
//            ourRealSells = clearingParams.get("sells").toString();
//        }
//
//        Map<String, String> params = new HashMap<>(10);
//        params.put("orderId", orderId);
//        params.put("accNo", accNo);
//        params.put("Name", Name);
//        params.put("txnAmt", longRateAmt.toString());//TODO 修改为清算金额
//        params.put("certificateCode", idCarNo);
//
//        //用户，交易类型，时间来更改订单状态，订单号，清算状态，
//        Map<String, String> clearState1 = new HashMap<>(15);
//        clearState1.put("userId", userId);
//        clearState1.put("transType", transType);
//        clearState1.put("createTime", createTime);
//        clearState1.put("orderCount", orderCount);
//        clearState1.put("orderId", orderId);
//        clearState1.put("timeStamp", "");
//        clearState1.put("resultCode", "ZC");
//        clearState1.put("accNo",  accNo);
//        clearState1.put("resultDesc", "正在申请代付");
//        clearState1.put("rateAmt", rateAmt);
//        clearState1.put("txnAmt", txnAmt);
//        clearState1.put("merId", merId);
//        clearState1.put("verify", "true");
//        clearState1.put("clearingType", clearingType);
//        clearingService.updateClearingState(clearState1);
//
//
//        MinShengClearingResponseDTO minShengClearingResponseDTO = null;
//        if (transType.equals("3")) {//银联
//            minShengClearingResponseDTO = shcs_DaiFu.DaifuJiaoYi(params);
//        } else {//微信支付宝
//            minShengClearingResponseDTO = WeiZhi_DaiFu.DaifuJiaoYi(params);
//        }
//        //用户，交易类型，时间来更改订单状态，订单号，清算状态，
//        Map<String, String> clearState = new HashMap<>(15);
//        clearState.put("userId", userId);
//        clearState.put("transType", transType);
//        clearState.put("createTime", createTime);
//        clearState.put("orderCount", orderCount);
//        clearState.put("orderId", orderId);
//        clearState.put("timeStamp", minShengClearingResponseDTO.getTimeStamp() == null ? "" : minShengClearingResponseDTO.getTimeStamp());
//        clearState.put("resultCode", minShengClearingResponseDTO.getResultCode() == null ? "00" : minShengClearingResponseDTO.getResultCode());
//        clearState.put("accNo", minShengClearingResponseDTO.getAccNo()  == null ? null : minShengClearingResponseDTO.getAccNo() );
//        clearState.put("resultDesc", minShengClearingResponseDTO.getResultDesc()  == null ? "请查询结果" : minShengClearingResponseDTO.getResultDesc());
//        clearState.put("rateAmt", rateAmt);
//        clearState.put("txnAmt", txnAmt);
//        clearState.put("merId", merId);
//        clearState.put("clearingType", clearingType);
//        clearState.put("verify", minShengClearingResponseDTO.getVerify().toString()  == null ? "0" : minShengClearingResponseDTO.getVerify().toString());
//        clearState.put("isUpdate", "true");
//        clearState.put("cost", clearingParams.get("cost").toString());
//        clearState.put("sells", ourRealSells);
//        clearingService.updateClearingState(clearState);
//        responseDTO.setData(minShengClearingResponseDTO);
//        responseDTO.setSuccess(true);
//        responseDTO.setMessage("操作成功");
//        return responseDTO;
//    }
//
//    /**
//     * 民生银行代付异步通知接口--银联
//     *
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping(value = "/daiFuAsyncNotification", method = {RequestMethod.POST, RequestMethod.GET})
//    public void daiFuAsyncNotification(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        try {
//            StringBuffer sb = new StringBuffer();
//            InputStream is = request.getInputStream();
//            InputStreamReader isr = new InputStreamReader(is);
//            BufferedReader br = new BufferedReader(isr);
//            String s = "";
//            while ((s = br.readLine()) != null) {
//                sb.append(s);
//            }
//            String str = sb.toString();
//            logger.info("银联-异步通知加密数据为：" + str);
//
//            if (str != null && !str.equals("")) {
//                String jieMi = shcs_DaiFu.jieMi(str);
//                logger.info("银联-异步通知解密数据为：" + jieMi);
//                MinShengClearingResponseDTO minShengClearingResponseDTO = shcs_DaiFu.generateMinShengClearingResponse(jieMi);
//                String msg = minShengClearingResponseDTO.getResultDesc();
//                //转码
//                String utf8 = URLDecoder.decode(msg, "utf-8");
//                minShengClearingResponseDTO.setResultDesc(utf8);
//                logger.info("银联-转换后的数据为：" + minShengClearingResponseDTO.toString());
//                // 更新数据库中的状态
//                clearingService.updateClearingOrderState(minShengClearingResponseDTO);
//            } else {
//
//            }
//
//            response.setContentType("text/html;charset=UTF-8");
//            logger.info("银联代付-异步通知成功");
//            response.getWriter().write("SUCCESS");
//        } catch (Exception e) {
//            response.setContentType("text/html;charset=UTF-8");
//            response.getWriter().write("FAIL");
//        }
//
//    }
//    /**
//     * 民生银行代付异步通知接口--微信支付宝
//     *
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping(value = "/daiFuAsyncNotificationWeiZhi", method = {RequestMethod.POST, RequestMethod.GET})
//    public void daiFuAsyncNotificationWeiZhi(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        try {
//            StringBuffer sb = new StringBuffer();
//            InputStream is = request.getInputStream();
//            InputStreamReader isr = new InputStreamReader(is);
//            BufferedReader br = new BufferedReader(isr);
//            String s = "";
//            while ((s = br.readLine()) != null) {
//                sb.append(s);
//            }
//            String str = sb.toString();
//            logger.info("微信支付宝-异步通知加密数据为：" + str);
//
//            if (str != null && !str.equals("")) {
//                String jieMi = WeiZhi_DaiFu.jieMi(str);
//                logger.info("微信支付宝-异步通知解密数据为：" + jieMi);
//                MinShengClearingResponseDTO minShengClearingResponseDTO = WeiZhi_DaiFu.generateMinShengClearingResponse(jieMi);
//                String msg = minShengClearingResponseDTO.getResultDesc();
//                //转码
//                String utf8 = URLDecoder.decode(msg, "utf-8");
//                minShengClearingResponseDTO.setResultDesc(utf8);
//                logger.info("微信支付宝-转换后的数据为：" + minShengClearingResponseDTO.toString());
//                // 更新数据库中的状态
//                clearingService.updateClearingOrderState(minShengClearingResponseDTO);
//            } else {
//
//            }
//
//            response.setContentType("text/html;charset=UTF-8");
//            logger.info("微信支付宝代付-异步通知成功");
//            response.getWriter().write("SUCCESS");
//        } catch (Exception e) {
//            response.setContentType("text/html;charset=UTF-8");
//            response.getWriter().write("FAIL");
//        }
//
//    }
//
//    /**
//     * 民生银行代付结果查询
//     *
//     * @param orderId
//     * @return
//     * @throws Exception
//     */
//    @RequiresPermissions("CLEARING:DO_CLEARING")
//    @RequestMapping(value = "/queryDaiFuResult", method = {RequestMethod.POST})
//    public @ResponseBody
//    ResponseDTO queryDaiFuResult(String orderId, String transType) throws Exception {
//        MinShengClearingResponseDTO minShengClearingResponseDTO;
//        ResponseDTO responseDTO = new ResponseDTO();
//        if ("3".equals(transType)) {
//            minShengClearingResponseDTO = shcs_DaiFu.DaifuChaxun(orderId);
//        } else {//微信支付宝
//            minShengClearingResponseDTO = WeiZhi_DaiFu.DaifuChaxun(orderId);
//        }
//        // 更新数据库中的状态
//        if (!"WM".equals(minShengClearingResponseDTO.getResultCode()))
//            clearingService.updateClearingOrderState(minShengClearingResponseDTO);
//        responseDTO.setMessage("查询成功");
//        responseDTO.setSuccess(true);
//        responseDTO.setData(minShengClearingResponseDTO);
//        return responseDTO;
//    }
//
//    /**
//     * 对账操作
//     *
//     * @return
//     * @throws Exception
//     */
//    @RequiresPermissions("CLEARING:DO_CLEARING")
//    @RequestMapping(value = "/reconciliation", method = {RequestMethod.GET, RequestMethod.POST})
//    public @ResponseBody
//    ResponseDTO reconciliation() throws Exception {
//        ResponseDTO responseDTO = new ResponseDTO();
//        Map<String, Map<String, String>> datas = new HashMap<>(3);
//        /**
//         * 对账逻辑：
//         *  把所有对账信息都对账，做到总的成功了，分到天就成功了
//         **/
//        //1.
//        //获取到所有商户号
//        JSONObject jsonObject = JSONObject.fromObject(shcs_DaiFu.merIds);
//        System.out.println(jsonObject.toString());
//        JSONArray uPayMerIds = (JSONArray) jsonObject.get("uPay");
//        for (Object s : uPayMerIds) {
//            String merId = (String) s;
//            System.out.println(merId);
//            Map<String, String> uPaySt = clearingService.reconciliation(merId);
//            if (!"00".equals(uPaySt.get("code"))) { //对账失败
//                datas.put("uPay", uPaySt);
//                break;
//            }
//        }
//        JSONArray wzMerIds = (JSONArray) jsonObject.get("wxZfb");
//        for (Object s : wzMerIds) {
//            String merId = (String) s;
//            System.out.println(merId);
//            Map<String, String> wxZfbSte = clearingService.reconciliation(merId);
//            if (!"00".equals(wxZfbSte.get("code"))) { //对账失败
//                datas.put("wxZfb", wxZfbSte);
//                break;
//            }
//        }
//        responseDTO.setSuccess(true);
//        responseDTO.setMessage("对账完成");
//        responseDTO.setData(datas);
//        responseDTO.setCode(HttpRequestConstant.REQUEST_SUCCESS_CODE);
//        return responseDTO;
//    }
//
//    /**
//     * 跳转到订单清算页面
//     *
//     * @return
//     * @throws Exception
//     */
//    @RequiresPermissions("CLEARING:DO_CLEARING")
//    @RequestMapping(value = "/clearingOrderPage", method = {RequestMethod.GET, RequestMethod.POST})
//    public String clearingOrderPage() throws Exception {
//        return "content/clearing/clearing";
//    }
//
//    /**
//     * 查询所有清算订单信息
//     *
//     * @return
//     * @throws Exception
//     */
//    @RequiresPermissions("CLEARING:DO_CLEARING")
//    @RequestMapping(value = "/selectNotClearingOrder", method = {RequestMethod.GET, RequestMethod.POST})
//    public @ResponseBody
//    ResponseDTO selectNotClearingOrder() throws Exception {
//        ResponseDTO responseDTO = new ResponseDTO();
//        responseDTO.setData(clearingService.selectNotClearingOrder());
//        responseDTO.setMessage("获取成功");
//        responseDTO.setSuccess(true);
//        responseDTO.setCode(HttpRequestConstant.REQUEST_SUCCESS_CODE);
//        return responseDTO;
//    }
//}
